<?php

/**
 * Class Core_Task
 * @package Core
 */
abstract class Core_Task extends Core_Application {

    public function println($str = '', $log = true) {
        $msg = '[' . date('Y-m-d H:i:s') . '] ' . $str;
        echo $msg . "\n";
        if ($log) {
            Core_Log::log($str, 'Task_' . $this->request->getCmd());
        }
    }

    public function shellExec($cmd, $nohup = true) {
        $cmd = escapeshellcmd($cmd);
        if ($nohup) {
            $cmd = 'nohup ' . $cmd . ' > /dev/null 2>&1 &';
        }
        $this->println('Shell: ' . $cmd);
        $output = array();
        $return_var = null;
        exec($cmd, $output, $return_var);
        return array(
            'output' => $output,
            'return_var' => $return_var
        );
    }

    public function daemon($func_name, $args) {
        $pid = pcntl_fork();
        if ($pid) {
            pcntl_wait($status);
        } else {
            if ($pid == -1) {
                throw new Exception('Couldn\'t create child process');
            } else {
                $pid = pcntl_fork();
                if ($pid == 0) {
                    posix_setsid();
                    call_user_func_array($func_name, $args);
                    exit(0);
                } else {
                    if ($pid == -1) {
                        throw new Exception('Couldn\'t create child process');
                    } else {
                        sleep(1);
                        exit(0);
                    }
                }
            }
        }
    }

}